<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <el-form-item label="奖品名称:" prop="prizeType">
        <el-radio v-model="dataForm.prizeType" label="1">学分</el-radio>
        <el-input v-model="dataForm.prizePrice" v-if="dataForm.prizeType==1" placeholder="学分" style="width:150px"></el-input>
        <el-radio v-model="dataForm.prizeType" label="2">其他</el-radio>
        <el-input v-model="dataForm.prizeName" v-if="dataForm.prizeType==2" placeholder="其他" style="width:180px"></el-input>
      </el-form-item>
      <el-form-item label="奖品图片:" prop="prizeCoverUrl">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleimgSuccess"
          :before-upload="beforeimgUpload"
        >
          <img v-if="dataForm.prizeCoverUrl" :src="dataForm.prizeCoverUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-loading="dataList">确定</el-button>
    </span>
  </el-dialog>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
export default {
  data() {
    return {
      visible: false,
      dataList: false,
      dataForm: {
        id: 0,
        prizeType:'1',
        prizeName:'',
        prizeCoverUrl:'',
        prizePrice:'',
      },
      dataRule: {
        prizeCoverUrl:[
           { required: true, message: "上传图片不能为空", trigger: "blur" },
        ]
      },
      uploadUrl: ""
    };
  },
  mounted() {
    this.uploadUrl = this.$http.adornUrl(
      `/lotterySurvey/lotteryprize/upload?token=${this.$cookie.get(
        "token"
      )}`
    );
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/lotterySurvey/lotteryprize/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
                this.dataForm.prizeCoverUrl = data.lotteryPrize.prizeCoverUrl;
                this.dataForm.prizeType = data.lotteryPrize.prizeType+'';
                this.dataForm.prizePrice = data.lotteryPrize.prizePrice;
                this.dataForm.prizeName = data.lotteryPrize.prizeName;
            }
          });
        }
      });
    },
    // 上传奖品图片
    handleimgSuccess(res, file) {
      this.dataForm.prizeCoverUrl = res.url;
    },
    beforeimgUpload(file) {
      const isJPG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 /1024 < 3;
      if (!isJPG) {
        this.$message.error("上传封面只能是 png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传封面大小不能超过 250kb!");
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = 540;
        let height = 360;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error("上传的奖品图必须是540*360!");
          return Promise.reject();
        }
      );
      return isJPG && isLt2M && isSize;
    },
    // 表单提交
    dataFormSubmit() {
      if(this.dataForm.prizeType==1&&this.dataForm.prizePrice==""){
          this.$message({
          message: '学分不能为空',
          type: 'warning'
        })
        return
      }else if(this.dataForm.prizeType==2&&this.dataForm.prizeName==""){
        this.$message({
          message: '奖品名称不能为空',
          type: 'warning'
        })
        return
      }else if(!this.dataForm.prizeCoverUrl){
        this.$message({
          message: '请上传奖品图片',
          type: 'warning'
        })
        return
      }else if(this.dataForm.prizeType==1){
        this.dataForm.prizeName = this.dataForm.prizePrice+'学分';
      }
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/lotterySurvey/lotteryprize/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              prizeCoverUrl:this.dataForm.prizeCoverUrl,
              prizeType:this.dataForm.prizeType,
              prizeName:this.dataForm.prizeName,
              prizePrice:this.dataForm.prizePrice,
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.dataList = false;
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              // this.dataList = true
              this.dataList = false;
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
